package com.example.iot;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


public class MainActivity extends AppCompatActivity {

    WebView mWebView;
    TextView statusText;
    boolean isErrorThisTime = false;
    class WebViewClientDemo extends WebViewClient {
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            // 这个方法在 android 6.0才出现
            int statusCode = errorResponse.getStatusCode();
            /*if (404 == statusCode || 500 == statusCode) {
                webView.setVisibility(View.INVISIBLE);
                statusText.setText("无法连接服务器：" + request.getUrl() + "：" + request.getMethod() + errorResponse.getStatusCode());
                statusText.setVisibility(View.VISIBLE);
            }*/
            Log.w("IoT-Web", "onReceivedHttpError: request Url" + request.getUrl() + ", request Method: " + request.getMethod() + ", status code: " + errorResponse.getStatusCode());
        }
        @Override
        public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
            super.onReceivedError(webView, webResourceRequest, webResourceError);
            //if (webResourceRequest.isForMainFrame()) {//是否是为 main frame创建
                mWebView.setVisibility(View.GONE);
                statusText.setText("无法连接服务器：" + webResourceError.getErrorCode() + ", " + webResourceError.getDescription());
                statusText.setVisibility(View.VISIBLE);
            //}
            isErrorThisTime = true;
            Log.w("IoT-Web", "onReceivedError");
        }
        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!isErrorThisTime) {
                statusText.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);
            }
        }
    }
    private static final int REQUEST_CODE_MEDIA_PERMISSIONS = 123;

    @SuppressLint("LongLogTag")
    public static Bitmap GetFramePictures(String url, long timeUs){
  Bitmap videoShortCut = null;
  String width;
  String height;
  MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
  try {
    if (url != null) {
      HashMap<String, String> headers;
      headers = new HashMap<>();
      headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
      mediaMetadataRetriever.setDataSource(url, headers);
    } else {
      //mmr.setDataSource(mFD, mOffset, mLength);
     }
    videoShortCut = mediaMetadataRetriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST);
    width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    Log.d("--使用MediaMetadata方式--","图片高度为：" + width + "图片宽度为：" + height);

   } catch (IllegalArgumentException e) {
    Log.e("setFrameAtTimeWithView ERROR:" , e.toString(), e);
   }
        try {
            mediaMetadataRetriever.release();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return videoShortCut;
    }

    private void saveBitmapToMediaStore(Context context, Bitmap bitmap) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "image_" + System.currentTimeMillis() + ".jpg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES); //Optional Relative Path

        ContentResolver resolver = context.getContentResolver();
        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        try {
            if (uri != null) {
                OutputStream outputStream = resolver.openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
                outputStream.close();
                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "Uri is null", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Toast.makeText(context, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        statusText = (TextView)findViewById(R.id.text_status);
        statusText.setText("正在连接");

        Button refreshButton = (Button)findViewById(R.id.button_refresh);
        refreshButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                isErrorThisTime = false;
                statusText.setText("正在连接");
                statusText.setVisibility(View.VISIBLE);
                mWebView.setVisibility(View.GONE);
                mWebView.reload();
            }
        });

        Button saveImgButton = (Button)findViewById(R.id.button_download_img);
        saveImgButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                String fileName = simpleDateFormat.format(date);
                //mWebView.loadUrl("javascript:(function(){var img = document.getElementById('image-vangogh');if (!img) return; var url = img.src; var aaaa = document.createElement('aaaa'); aaaa.href = img.src; aaaa.target='_blank'; aaaa.download='" + fileName + ".jpg'; var fakeEvent = document.createEvent('Event'); fakeEvent.initEvent('click', true, true); aaaa.dispatchEvent(fakeEvent); (window.URL || window.webkitURL).revokeObjectURL(aaaa.href);})()");
                RequestOptions options = new RequestOptions();

//                Glide.with(getApplicationContext()).downloadOnly().load("http://1.94.38.43:6002/video_feed"/*"https://www.dofactory.com/img/html/vangogh.jpg"*/).listener(new RequestListener<File>() {
//                    @Override
//                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<File> target, boolean isFirstResource) {
//                        Toast.makeText(getApplicationContext(), "无法访问："+e.getMessage() + "\n" + e.getCauses(), Toast.LENGTH_SHORT).show();
//                        return false;
//                    }
//
//                    @Override
//                    public boolean onResourceReady(@NonNull File resource, @NonNull Object model, Target<File> target, @NonNull DataSource dataSource, boolean isFirstResource) {
//                        InputStream inputStream = null;
//                        try {
//                            inputStream = new FileInputStream(resource);
//                        } catch (FileNotFoundException e) {
//                            throw new RuntimeException(e);
//                        }
//                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//                        saveBitmapToMediaStore(getApplicationContext(), bitmap);
//                        return false;
//                    }
//
//                }).preload();
//                String DownloadImageURL = "http://1.94.38.43:6002/video_feed";
//                if (URLUtil.isValidUrl(DownloadImageURL)) {
//                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
//                    request.allowScanningByMediaScanner();
//                    //设置图片的保存路径
////                    request.setDestinationInExternalFilesDir(MainActivity.this, "/img", "/a.png");
//                    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//                    downloadManager.enqueue(request);
//                    Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_LONG).show();
//                } else {
//                    Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_LONG).show();
//                }
//                saveBitmapToMediaStore(getApplicationContext(), GetFramePictures("http://1.94.38.43:6002/video_feed", 0));

                try {
                    mWebView.setDrawingCacheEnabled(true);
                    mWebView.buildDrawingCache();
                    Bitmap bitmap = Bitmap.createBitmap(mWebView.getDrawingCache());
                    mWebView.setDrawingCacheEnabled(false);
                    saveBitmapToMediaStore(getApplicationContext(), bitmap);
                    //Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "请重试", Toast.LENGTH_LONG).show();
                }
            }
        });
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebViewClientDemo());
//        webView.setWebChromeClient(new WebChromeClient());
//        webView.setWebViewClient();
        String url = "1.94.38.43:6002";
//        String url = "https://www.dofactory.com/html/img/id";
        isErrorThisTime = false;
        mWebView.loadUrl(url);
    }
}
